<template>
  <div class="dashboard-container">
    <!-- 欢迎信息 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="welcome-card">
          <div class="welcome-content">
            <div class="welcome-text">
              <h2>欢迎回来，{{ driverName }}</h2>
              <p>{{ greetingMessage }}</p>
            </div>
            <div class="driver-info">
              <div class="info-item">
                <span class="label">司机ID:</span>
                <span class="value">{{ driverInfo.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">评分:</span>
                <span class="value">
                  <el-rate v-model="driverInfo.rating" disabled text-color="#ff9900"></el-rate>
                  <span class="rating-value">{{ driverInfo.rating }}</span>
                </span>
              </div>
              <div class="info-item">
                <span class="label">认证状态:</span>
                <span class="value">
                  <el-tag type="success" v-if="driverInfo.verified">已认证</el-tag>
                  <el-tag type="warning" v-else>未认证</el-tag>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">今日收入</div>
              <div class="data-value">¥{{ statistics.todayIncome }}</div>
              <div class="data-compare">
                较昨日
                <span :class="statistics.incomeCompare >= 0 ? 'up' : 'down'">
                  {{ statistics.incomeCompare >= 0 ? '+' : '' }}{{ statistics.incomeCompare }}%
                </span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#409EFF"><Money /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">今日订单</div>
              <div class="data-value">{{ statistics.todayOrders }}</div>
              <div class="data-compare">
                较昨日
                <span :class="statistics.ordersCompare >= 0 ? 'up' : 'down'">
                  {{ statistics.ordersCompare >= 0 ? '+' : '' }}{{ statistics.ordersCompare }}%
                </span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#67C23A"><Tickets /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">本月收入</div>
              <div class="data-value">¥{{ statistics.monthIncome }}</div>
              <div class="data-compare">
                已完成
                <span class="normal">{{ statistics.monthProgress }}%</span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#E6A23C"><Calendar /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">总行程</div>
              <div class="data-value">{{ statistics.totalTrips }}</div>
              <div class="data-compare">
                总里程 <span class="normal">{{ statistics.totalMileage }}km</span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#F56C6C"><Location /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表和最近订单 -->
    <el-row :gutter="20" class="mt-20">
      <!-- 收入趋势图 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入趋势</span>
              <el-radio-group v-model="incomeChartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="incomeChartRef"></div>
        </el-card>
      </el-col>
      
      <!-- 最近订单 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="recent-orders-card">
          <template #header>
            <div class="card-header">
              <span>最近订单</span>
              <el-button type="text" @click="viewAllOrders">查看全部</el-button>
            </div>
          </template>
          <div class="recent-orders-list">
            <div v-if="recentOrders.length === 0" class="no-data">
              暂无订单数据
            </div>
            <div v-for="order in recentOrders" :key="order.id" class="order-item">
              <div class="order-info">
                <div class="order-title">{{ order.passengerName }} 的订单</div>
                <div class="order-route">{{ order.startLocation }} → {{ order.endLocation }}</div>
                <div class="order-time">{{ order.time }}</div>
              </div>
              <div class="order-amount">¥{{ order.amount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待处理事项和订单分析 -->
    <el-row :gutter="20" class="mt-20">
      <!-- 待处理事项 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="todo-card">
          <template #header>
            <div class="card-header">
              <span>待处理事项</span>
            </div>
          </template>
          <div class="todo-list">
            <div v-if="todoList.length === 0" class="no-data">
              暂无待处理事项
            </div>
            <div v-for="todo in todoList" :key="todo.id" class="todo-item">
              <el-icon class="todo-icon" :class="todo.type"><component :is="todo.icon"></component></el-icon>
              <div class="todo-content">
                <div class="todo-title">{{ todo.title }}</div>
                <div class="todo-desc">{{ todo.description }}</div>
              </div>
              <el-button size="small" type="primary" @click="handleTodo(todo)">处理</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 订单分析 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>订单分析</span>
            </div>
          </template>
          <div class="analysis-container" ref="orderAnalysisRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

const router = useRouter()

// 司机信息
const driverName = ref('张师傅')
const driverInfo = reactive({
  id: 'D10086',
  rating: 4.8,
  verified: true
})

// 欢迎语
const greetingMessage = ref('祝您今天工作顺利！')
onMounted(() => {
  const hour = new Date().getHours()
  if (hour < 6) {
    greetingMessage.value = '夜深了，注意休息！'
  } else if (hour < 9) {
    greetingMessage.value = '早上好，祝您今天工作顺利！'
  } else if (hour < 12) {
    greetingMessage.value = '上午好，祝您今天工作顺利！'
  } else if (hour < 14) {
    greetingMessage.value = '中午好，记得休息一下哦！'
  } else if (hour < 18) {
    greetingMessage.value = '下午好，祝您工作愉快！'
  } else if (hour < 22) {
    greetingMessage.value = '晚上好，辛苦一天了！'
  } else {
    greetingMessage.value = '夜深了，注意休息！'
  }

  // 从本地存储获取用户名
  const storedUsername = localStorage.getItem('username')
  if (storedUsername) {
    driverName.value = storedUsername
  }
})

// 统计数据
const statistics = reactive({
  todayIncome: 345.5,
  incomeCompare: 5.2,
  todayOrders: 8,
  ordersCompare: -2.1,
  monthIncome: 4589.75,
  monthProgress: 65,
  totalTrips: 128,
  totalMileage: 1256.8
})

// 最近订单数据
const recentOrders = reactive([
  {
    id: 'O2023051001',
    passengerName: '李同学',
    startLocation: '校园北门',
    endLocation: '火车站',
    time: '今天 08:30',
    amount: 25.5
  },
  {
    id: 'O2023051002',
    passengerName: '王同学',
    startLocation: '图书馆',
    endLocation: '华联商场',
    time: '今天 10:15',
    amount: 18.0
  },
  {
    id: 'O2023051003',
    passengerName: '赵同学',
    startLocation: '学生公寓',
    endLocation: '市中心',
    time: '今天 14:45',
    amount: 35.0
  }
])

// 待办事项
const todoList = reactive([
  {
    id: 1,
    title: '资质认证即将到期',
    description: '您的驾驶证认证将在7天后到期，请及时更新',
    type: 'warning',
    icon: 'Warning',
    link: '/driver/qualification'
  },
  {
    id: 2,
    title: '新的订单评价',
    description: '您有3条新的订单评价未查看',
    type: 'info',
    icon: 'ChatDotRound',
    link: '/driver/orders'
  }
])

// 处理待办事项
const handleTodo = (todo) => {
  router.push(todo.link)
}

// 查看全部订单
const viewAllOrders = () => {
  router.push('/driver/orders')
}

// 收入图表相关
const incomeChartRef = ref(null)
let incomeChart = null
const incomeChartType = ref('week')

// 监听图表类型变化
watch(incomeChartType, (newVal) => {
  initIncomeChart()
})

// 初始化收入图表
const initIncomeChart = () => {
  if (!incomeChartRef.value) return
  
  if (incomeChart) {
    incomeChart.dispose()
  }
  
  incomeChart = echarts.init(incomeChartRef.value)
  
  let xAxisData = []
  let seriesData = []
  
  if (incomeChartType.value === 'week') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    seriesData = [120, 132, 101, 134, 90, 230, 210]
  } else {
    xAxisData = Array.from({length: 30}, (_, i) => i + 1)
    seriesData = [
      120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 
      134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 
      210, 120, 132, 101, 134, 90, 230, 210, 120, 132
    ]
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: seriesData,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  incomeChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    incomeChart.resize()
  })
}

// 订单分析图表
const orderAnalysisRef = ref(null)
let orderAnalysisChart = null

const initOrderAnalysisChart = () => {
  if (!orderAnalysisRef.value) return
  
  if (orderAnalysisChart) {
    orderAnalysisChart.dispose()
  }
  
  orderAnalysisChart = echarts.init(orderAnalysisRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 'bottom'
    },
    series: [
      {
        name: '订单类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 45, name: '校内短途' },
          { value: 27, name: '市区中途' },
          { value: 15, name: '跨区长途' },
          { value: 13, name: '其他' }
        ]
      }
    ]
  }
  
  orderAnalysisChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    orderAnalysisChart.resize()
  })
}

// 组件挂载后初始化图表
onMounted(() => {
  initIncomeChart()
  initOrderAnalysisChart()
})
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  max-width: 100%;
  min-height: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #1890ff 0%, #409EFF 100%);
  color: white;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.welcome-text {
  flex: 1;
  min-width: 250px;
}

.welcome-text h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 24px;
  color: white;
}

.welcome-text p {
  margin: 0;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

.driver-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.info-item .label {
  color: rgba(255, 255, 255, 0.8);
  margin-right: 10px;
}

.info-item .value {
  font-weight: 500;
  display: flex;
  align-items: center;
  color: white;
}

.rating-value {
  margin-left: 5px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
  overflow: hidden;
}

.data-card-content {
  display: flex;
  padding: 20px;
  height: 100%;
}

.data-card-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.data-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.data-compare {
  font-size: 13px;
  color: #909399;
}

.data-compare .up {
  color: #67C23A;
}

.data-compare .down {
  color: #F56C6C;
}

.data-compare .normal {
  color: #409EFF;
}

.data-card-right {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.chart-card, .recent-orders-card, .todo-card, .analysis-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart-container, .analysis-container {
  height: 340px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-orders-list, .todo-list {
  height: 340px;
  overflow-y: auto;
}

.order-item, .todo-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #EBEEF5;
  align-items: center;
}

.order-item:last-child, .todo-item:last-child {
  border-bottom: none;
}

.order-info {
  flex: 1;
}

.order-title, .todo-title {
  font-weight: 500;
  margin-bottom: 5px;
}

.order-route, .todo-desc {
  color: #909399;
  font-size: 13px;
}

.order-time {
  color: #C0C4CC;
  font-size: 12px;
  margin-top: 5px;
}

.order-amount {
  font-weight: bold;
  color: #F56C6C;
}

.todo-icon {
  margin-right: 15px;
  font-size: 20px;
}

.todo-content {
  flex: 1;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .chart-card, .recent-orders-card, .todo-card, .analysis-card {
    height: auto;
    min-height: 300px;
  }
  
  .chart-container, .analysis-container {
    height: 280px;
  }
  
  .recent-orders-list, .todo-list {
    height: auto;
    max-height: 280px;
  }
}

@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
  }
  
  .driver-info {
    margin-top: 20px;
  }
  
  .info-item {
    margin-bottom: 8px;
  }
  
  .data-card {
    height: 100px;
  }
  
  .data-card-content {
    padding: 15px;
  }
  
  .data-value {
    font-size: 20px;
  }
  
  .chart-container, .analysis-container {
    height: 220px;
  }
}
</style> 